package com.qiantu.phone.ui.activity;

import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.ElecPriceBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomSetTimePeriodDialog;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;

public class EnergyDillActivity extends AppActivity {
    private ElecPriceBean mElcPriceData;
    private android.widget.CheckBox checkbox1;
    private android.widget.CheckBox checkbox2;
    private com.hjq.widget.layout.SettingBar eBillSet;
    private ViewGroup eBillSetLy;
    private androidx.recyclerview.widget.RecyclerView list;
    private com.hjq.shape.view.ShapeTextView addDillItemBtn;
    ElecPriceAdapter elecPriceAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_energy_dill;
    }

    @Override
    protected void initView() {
        checkbox1 = findViewById(R.id.checkbox_1);
        checkbox2 =  findViewById(R.id.checkbox_2);
        eBillSet = findViewById(R.id.e_bill_set);
        eBillSetLy = findViewById(R.id.e_bill_set_ly);
        list =  findViewById(R.id.list);
        addDillItemBtn = findViewById(R.id.add_dill_item_btn);
        list.setLayoutManager(new LinearLayoutManager(this));
        elecPriceAdapter = new ElecPriceAdapter();
        list.setAdapter(elecPriceAdapter);
        elecPriceAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                mEditStage = mElcPriceData.stageConfigurations.get(position);
                mEditStagePosition = position;
                if (view.getId() == R.id.bill){
                    showBottomEditDialog();
                }else if (view.getId() == R.id.time){
                    showBottomTimePeriodDialog();
                }else if (view.getId() == R.id.delete){
                    mElcPriceData.removeStagePosition(position);
                    elecPriceAdapter.notifyDataSetChanged();
                }
            }
        });
        selectBillType(1);
        setOnClickListener(checkbox1, checkbox2, eBillSet, addDillItemBtn);
    }

    @Override
    protected void initData() {
        mElcPriceData = new ElecPriceBean();
        mElcPriceData.calculateType = 1;
        if (mElcPriceData.stageConfigurations == null || mElcPriceData.stageConfigurations.size()<2){
            mElcPriceData.stageConfigurations = new ArrayList<>();
            mElcPriceData.stageConfigurations.add(new ElecPriceBean.StageConfigurationBean(1));
            mElcPriceData.stageConfigurations.add(new ElecPriceBean.StageConfigurationBean(2));
        }
        elecPriceAdapter.setNewInstance(mElcPriceData.stageConfigurations);
        updateUi();
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        LLHttpManager.setElecPrice(getAppActivity(), mElcPriceData, new HttpCallback<HttpData<Void>>(getAppActivity()){
            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                finish();
            }
        });
    }

    private void updateUi(){
        LLHttpManager.getElecPrice(getAppActivity(), AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<ElecPriceBean>>(getAppActivity()){
        @Override
        public void onSucceed(HttpData<ElecPriceBean> result) {
            super.onSucceed(result);
                if (result.getData() == null) return;
                mElcPriceData = result.getData();
                selectBillType(mElcPriceData.calculateType);
                eBillSet.setRightText(getElecPricStr(mElcPriceData.price));
                if (mElcPriceData.stageConfigurations == null || mElcPriceData.stageConfigurations.isEmpty()){
                    mElcPriceData.addNewStage(2);
                }
                elecPriceAdapter.setNewInstance(mElcPriceData.stageConfigurations);
            }
        });
    }

    private String getElecPricStr(float value){
        if (value == 0) return "";
        String str = String.format("%.2f", value);
        str = TextUtils.isEmpty(str) ? "" : str + " " +getString(R.string.elec_price_unit);
        return str;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == checkbox1){
            selectBillType(1);
        }else if (view == checkbox2){
            selectBillType(2);
        }else if (view == eBillSet){
            showBottomEditDialog();
        }else if (view == addDillItemBtn){
            mElcPriceData.addNewStage();
            elecPriceAdapter.notifyItemInserted(mElcPriceData.stageConfigurations.size());
        }
    }

    private void selectBillType(int i){
        if (i == 1){
            checkbox1.setChecked(true);
            checkbox2.setChecked(false);
            list.setVisibility(View.GONE);
            addDillItemBtn.setVisibility(View.GONE);
            eBillSetLy.setVisibility(View.VISIBLE);
        }else {
            checkbox1.setChecked(false);
            checkbox2.setChecked(true);
            list.setVisibility(View.VISIBLE);
            addDillItemBtn.setVisibility(View.VISIBLE);
            eBillSetLy.setVisibility(View.GONE);
        }
        if (mElcPriceData != null){
            mElcPriceData.calculateType = i;
        }
    }

    private class ElecPriceAdapter extends BaseQuickAdapter<ElecPriceBean.StageConfigurationBean, BaseViewHolder>{
        public ElecPriceAdapter() {
            super(R.layout.elec_item_ly);
            addChildClickViewIds(R.id.time, R.id.bill, R.id.delete);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, ElecPriceBean.StageConfigurationBean item) {
            holder.setVisible(R.id.delete, holder.getAbsoluteAdapterPosition()>=2);
            holder.setText(R.id.title, String.format(getString(R.string.elec_price_period), item.section));
            ((SettingBar)holder.findView(R.id.bill)).setRightText(getElecPricStr(item.price));
            ((SettingBar)holder.findView(R.id.time)).setRightText(item.getTimeStr());
        }
    }


    private BottomEditDialog mBottomEditDialog;
    private ElecPriceBean.StageConfigurationBean mEditStage;
    private int mEditStagePosition;
    private void showBottomEditDialog() {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            mBottomEditDialog.setMaxLength(16);
            mBottomEditDialog.setLabel(getString(R.string.electricity_price));
            mBottomEditDialog.setOnConfirmDismiss(false);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    float value = Float.parseFloat(mBottomEditDialog.getText());
                    if(value <= 0){
                        toast("电价不能小于或等于0");
                    }else{
                        if (mElcPriceData.calculateType == 1){//固定电价
                            mElcPriceData.price = value;
                            eBillSet.setRightText(getElecPricStr(mElcPriceData.price));
                        }else {
                            mEditStage.price = value;
                            elecPriceAdapter.notifyItemChanged(mEditStagePosition);
                        }
                        mBottomEditDialog.dismiss();
                    }
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        if (mElcPriceData.calculateType == 1){//固定电价
            mBottomEditDialog.setText(mElcPriceData.price==0 ? "" : String.format("%.2f", mElcPriceData.price));
        }else {
            mBottomEditDialog.setText(mEditStage.price==0 ? "" : String.format("%.2f", mEditStage.price));
        }
        mBottomEditDialog.show();
    }

    private BottomSetTimePeriodDialog mBottomTimePeriodDialog;
    private void showBottomTimePeriodDialog(){
        if (mBottomTimePeriodDialog == null) {
            mBottomTimePeriodDialog = new BottomSetTimePeriodDialog(this);
            mBottomTimePeriodDialog.setDialogClickListener(new BottomSetTimePeriodDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int startHour, int startMinute, int endtHour, int endMinute) {
                    mEditStage.startHour = startHour;
                    mEditStage.startMinute = startMinute;
                    mEditStage.endtHour = endtHour;
                    mEditStage.endMinute = endMinute;
                    mBottomTimePeriodDialog.dismiss();
                    elecPriceAdapter.notifyItemChanged(mEditStagePosition);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomTimePeriodDialog);
        }

        mBottomTimePeriodDialog.setSelectedTime(mEditStage.startHour, mEditStage.startMinute, mEditStage.endtHour, mEditStage.endMinute);
        mBottomTimePeriodDialog.show();
    }
}